<template>
<div>
  <el-card class="search-card">
    <BasicForm
      ref="formData"
      :formColumns="formItemList"
      :dataSource="formData"
      :defaultExpandStatus="false"
      :handleSearchForm="handleQueryForm"
      :colNumOfRow="4"
      @getFormData="getFormData"
    />
  </el-card>
  <el-card class="table-card">
    <BasicTable
      showIndexCol
      showActionCol
      :showSelectCol="false"
      :loading="tableInfo.loading"
      :columns="tableInfo.columns"
      :dataSource="tableInfo.list"
      :pagination="pagination"
      :tableHeight="445"
      :actionColWidth="100"
      :actionRender="renderTableBtnAction"
      @pageChange="handlePageChange"
      @pageSizeChange="handlePageSizeChange"
    />
  </el-card>
</div>
</template>
<script>
import Cookies from 'js-cookie';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import BasicForm from '@/components/supplier/BasicForm';
import BasicTable from '@/components/supplier/BasicTable';
import { FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';
import { getTableAction } from '@supplier/utils/btnsUtils';
import { getHasIndexTableData } from '@supplier/utils/bizUtils';
import {
  querySupplierContractListService,
  renewContractService
} from '@/api/supplier/management/supplierContract';
import Setting from '@/setting'
export default {
  mixins: [BasicPage, Dict],
  components: {
    BasicForm,
    BasicTable
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      formData: {
        contractCode: '', // 合同编号
        contractName: '', // 合同名称
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        supplierClassify: '', // 供应商分类
        supplierType: '', // 供应商类型
        contractType: '', // 合同类型
        contractStatus: '', // 合同状态
        contractTime: [], // 合同到期时间
        createUser: '', // 发起人
        createTime: []// 发起时间
      },
      tableInfo: {
        list: [],
        columns: TABLE_COLUMNS,
        loading: false
      },
      btnLoading: {
        export: false
      }
    }
  },
  computed: {
    // 表单入参
    formParams () {
      const [launchStartTime = '', launchEndTime = ''] = this.formData['createTime'] || [];
      const [contractStartTime = '', contractEndTime = ''] = this.formData['contractTime'] || [];
      let params = {
        ...this.formData,
        contractStartTime,
        contractEndTime,
        launchStartTime,
        launchEndTime
      };
      delete params.createTime;
      delete params.contractTime;
      return params;
    }
  },
  mounted () {
    this.handleQueryForm();
  },
  methods: {
    renderTableBtnAction (h, { row }) {
      const actionList = [];
      if (row.detailUrl) {
        actionList.push({ label: '查看', method: () => { this.handleView(row) }, hasAuth: true })
      }
      /* if (row.singleFlag == 0) {
        actionList.push({ label: '续签合同', method: this.handleRenewContract, hasAuth: true })
      } */
      return getTableAction({ h, row, actionList, showBtn: this.showBtn });
    },
    // 查看
    handleView (row) {
      const url = `${row.detailUrl}&uc_token=${Cookies.get('uc_token')}`
      window.open(url)
      this.renewContract(row);
    },
    // 续签合同
    handleRenewContract (row) {
      const hasOvertime = this.compareTime(row.contractEndTime);
      const content = `合同未到期，此时续签会有时间重叠的情况，请及时终止上一份合同，您确定这么做吗？`;
      if (hasOvertime) {
        this.$confirm(content,
          { title: '提示', type: 'warning' }
        ).then(() => {
          sessionStorage.setItem('buttonId', getBtnsId('续签合同'));
          this.renewContract(row);
        }).catch(() => {});
      } else {
        this.renewContract(row);
      }
    },
    async renewContract ({ id, supplierId, singleFlag }) {
      const data = { contractId: id, supplierId, operateType: 0, singleFlag };
      try {
        const res = await renewContractService(data, state => { this.tableInfo.loading = state });
        if (res) {
          const contractUrl = `${Setting.SUPPLIER_CONTRACT_HOST}${res.result.url}`
          window.open(contractUrl);
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 获取表单数据
    getFormData (formData) {
      this.formData = formData;
    },
    // 获取表单查询入参
    getParamsBySearchForm () {
      const { current, size } = this.pagination;
      return { ...this.formParams, current, size };
    },
    // 获取表格数据
    async getTableData () {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const res = await querySupplierContractListService(
        this.getParamsBySearchForm(),
        state => { this.tableInfo.loading = state }
      );
      if (res) {
        this.tableInfo.list = getHasIndexTableData(res.result?.records, this.pagination);
        this.pagination.total = res.result.total;
      }
    },
    compareTime (time) {
      const currentTime = new Date();
      const endTime = new Date(time);
      return currentTime.getTime() < endTime.getTime();
    },
  }
}
</script>
